<template>
	<view class="container">
		<u-form :model="form" ref="form" label-width="180">
			<view v-if="item.zt==2">
				<u-button 
				type="primary"
				plain
				size="medium"
				disabled="true"
				>已审批
				</u-button>
			</view>
			<u-form-item label="客户姓名:" prop="contact" required ><u-input v-model="form.contact" v-bind:disabled="this.controllShow"></u-input></u-form-item>
			<u-form-item label="手机号:" prop="phone" required @click="phoneNumber" ><u-input v-model="form.phone" v-bind:disabled="this.controllShow"></u-input></u-form-item>
			<!-- <u-form-item label="客户编码:" prop="customerNo"><u-input v-model="form.customerNo"></u-input></u-form-item> -->
			<u-form-item label="预约日期:" prop="bookDate" required v-bind:disabled="this.controllShow">
				<u-input v-model="form.bookDate" :clearable="this.controllShow" type="select" v-bind:disabled="this.controllShow" @click="dutyTimePickerVisible = true" />
				<u-picker
					mode="time"
					v-model="dutyTimePickerVisible"
					:params="{
						year: true,
						month: true,
						day: true
					}"
					@confirm="dutyTimePickerChange"
				></u-picker>
			</u-form-item>
			<!-- <u-form-item label="预约时间段:" prop="dutyTime2" required v-bind:disabled="this.controllShow">
				<u-input v-model="showForm.dutyTime2Show" type="select" @click="dutyTime2PickerVisible = true"></u-input>
				<u-select v-model="dutyTime2PickerVisible" :list="bookTimeRangeDict" @confirm="dutyTime2Confirm"></u-select>
			</u-form-item> -->
			<u-form-item label="是否到货:" prop="goodsType" required v-bind:disabled="this.controllShow">
				<u-radio-group v-model="form.goodsType" @change="whetherChange">
					<u-radio 
						@change="wheChange" 
						v-for="(item, index) in goodsTypeList" :key="item.key" 
						:name="item.key"
						:disabled="item.disabled"
					>
						{{item.name}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			
			<u-form-item label="安装地址:" prop="smc" required disabled="false">
				<city-picker class="picker" :value="form.smc" text-align="left" @city-change="cityChange">
				</city-picker>
				<!-- <u-input v-model="form.province"></u-input> -->
			</u-form-item>
			<u-form-item label="详细地址:" prop="address" required disabled="false"><u-input v-model="form.address" placeholder="县区/街道/门牌号"></u-input></u-form-item>
			<u-form-item label="购买型号:" prop="buyType" required disabled="false">
				<u-input v-model="form.buyType"></u-input>
			</u-form-item>
			<u-form-item label="安装数量:" prop="buyNum" required disabled="false">
				<u-number-box v-model="form.buyNum"></u-number-box>
			</u-form-item>
			<u-form-item label="安装类型:" prop="payType" required disabled="false">
				<u-radio-group v-model="form.payType" @change="radioGroupChange">
									<u-radio 
										@change="radioChange" 
										v-for="(item, index) in payTypeDict" :key="item.key" 
										:name="item.key"
										:disabled="item.disabled"
									>{{item.name}}</u-radio>
				</u-radio-group>					
				
			</u-form-item>
			<u-form-item label="服务金额:" prop="standardFee"  v-bind:disabled="this.controllShow">
				<u-input v-model="form.standardFee" disabled="true"></u-input>
			</u-form-item>
			<u-form-item label="附加金额:" prop="adjustmentFee"  v-bind:disabled="this.controllShow">
				<u-input v-model="form.adjustmentFee"></u-input>
			</u-form-item>
			<!-- <u-form-item label="机身码:" prop="mcuId"><u-input v-model="form.mcuId"></u-input></u-form-item> -->
			<u-form-item  label="备注:" label-width="130" prop="remark" v-bind:disabled="this.controllShow">
				<u-input v-model="form.remark"
				placeholder="已发货锁体、特殊配件、或故障描述"
				></u-input>
			</u-form-item>
			<u-form-item label="图片或视频:" v-bind:disabled="this.controllShow" >
			  <view class="actionimg">
				<view class="imagesupload">
				<u-upload
					v-model="form.photo"
					ref="uUpload1"
					:action="'/'"
					width="120"
					height="120"
					max-count="5"
					upload-text=" "
					:file-list="fileList"
					:auto-upload="false"
					@on-list-change="fileListChange"
				></u-upload>
				</view>				
				<view class="imagesphoto">
					<view v-for="(item,index) in form.photo" :key="index">
						<img :src="item" mode
						style="width: 120rpx;height: 120rpx;"></img>
					</view>
				</view>
			 </view>
				<u-input type="textarea" placeholder="门照片(正面/侧面-衬板/门照片-侧面)或故障视频/安装服务说明资料"
				></u-input>
			</u-form-item>
			<u-form-item label="本单金额:"  prop="totalFee">
				<u-input v-model="form.totalFee" disabled="true"/>
			</u-form-item>
			<u-form-item label="预充值金额(余额):" prop="confirmPrice" >
				<u-input v-model="form.confirmPrice" 
				v-bind:disabled="this.controllShow"
				disabled="true"
				 placeholder="金额已提交后台"/>
			</u-form-item>
			<!-- <u-form-item label="安装服务说明资料:" prop="record" v-bind:disabled="this.controllShow">
				<u-input v-model="form.record"></u-input>
			</u-form-item> -->
			
		</u-form>
		
		<view class="bottomOpeCon">
				<view class="flex justify-center" style="margin-bottom:20rpx">
					<view>
						<u-button 
						type="primary"
						size="medium"
						@click="draftClick"
						style="margin-right:25rpx"
						>
						暂存</u-button>
					</view>
					<view>
						<u-button 
						type="success"
						size="medium"
						@click="submitClick">
						提交</u-button>
					</view>
					
				</view>
			</view>
		
		
	</view>
</template>

<script>
import { _bookTimeRangeDict,_payTypeDict } from '@/utils/dict.js';
import CityPicker from '@/components/city-picker/city-picker.vue';
import { 
getOrderItemDetail,
appointPicOrderApiUrl,
_appointPrePrice,
 } from '../../api/agent.js';
import baseUrl from '../../config/url.js';
import { mapActions } from 'vuex';

let bookTimeRangeDict = Object.keys(_bookTimeRangeDict).map(key => {
	return {
		label: _bookTimeRangeDict[key],
		value: key
	};
});
export default {
	components: {
		CityPicker,
	},
	data() {
		return {
			
			disabled:false,
			controllShow:false,
			form: {
				photo:[],
				orderNumber:'',
				device:'',
				id:'',
				zt: '',
				No:'chenjianen',
				oldprice: '',
				contact: '',
				phone: '',
				bookDate: '',
				dutyTime2: '',
				// smc: '',
				address: '',
				mcuId: '',
				buyType: '',
				standardFee:0,
				adjustmentFee:0,
				remark:'',
				customerNo: '',
				orderNo: '',
				buyNum:1,
				// goodsType:"",
				totalFee:0,
				// confirmPrice:2000,
				confirmPrice:0,
				record:"",
				disable:'',
				smc:'',
				province:'',
				city:'',
				district:'',
				
			},
			goodsTypeList:[
				{
					key:'1',
					name: '是',
					disabled: false
				},
				{
					key:'2',
					name: '否',
					disabled: false
				},
				
			],
			// 预充值金额
			appointPrePrice: '',
			payTypeDict:_payTypeDict,
			fileList: [],
			showForm: {
				dutyTime2Show: ''
			},
			rules: {
				contact: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
				phone: [{ required: true,pattern: /^1[3456789]\d{9}$/, message: '请输入客户11位手机号', trigger: 'blur' }],
				bookDate: [{ required: true, message: '请选择预约日期', trigger: 'change' }],    
				// dutyTime2: [{ required: true, message: '请选择预约时间段', trigger: 'change' }],
				// goodsType: [{ required: true, message: '请选择是否到货', trigger: 'change' }],
				// smc: [{ required: true, message: '请选择省市区', trigger: 'change' }],
				address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
				buyType: [{ required: true, message: '请输入购买型号', trigger: 'blur' }],
				// payType: [{ required: true, message: '安装类型', trigger: 'change' }],
			},
			dutyTimePickerVisible: false,
			bookTimeRangeDict,
			dutyTime2PickerVisible: false
		};
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
		// this.form.customerNo = this.$store.state.user.userInfo.teamNo;
		this.form.No = this.$store.state.user.userInfo.No;
	},
	onLoad(options){
			this.queryDetailById(options.orderNumber);
	},
	
	created() {
		this.getMoney();
	},
	methods: {
		...mapActions({
			saveAppointOrder: 'agent/saveAppointOrder'
		}),
		...mapActions({
					updateSaveAppointOrder: 'agent/updateSaveAppointOrder'
				}),
		// 拿id
		queryDetailById(orderNumber){
			getOrderItemDetail(orderNumber).then(response=>{
				this.form=response.data;
				this.form.oldprice=this.form.standardFee/this.form.buyNum
				var str=this.form.photo.split(";");
				this.form.photo=str;
				for (let st in str) {
					if(st<str.length-1){
						console.info(str[st])
						// this.form.photo.push({"url":baseUrl+"/"+str[st]});
						this.form.photo[st]=baseUrl+"/"+str[st];
						
					}
					// this.form.photo[st]="http://app.aptenon.com/tmr/"+str[st]	
				}
				console.log(this.form.photo);
				console.log(this.fileList);
				this.fileList=this.form.photo;
				this.form.photo.pop();
			})
		},
		
		wheChange(e){
			// 选中安装 
		},
		whetherChange(e){
			console.log(e);
			let radio;
			this.goodsTypeList.map(item=>{
				if(item.key==e){
					radio = item;
				}
			});
			console.log(radio); 
		},
		// 选中某个单选框时，由radio时触发
		radioChange(e) {
			// console.log(e);
		},
		// 选中任一radio时，由radio-group触发 
		radioGroupChange(e) {
			console.log(e);
			let radio;
			this.payTypeDict.map(item=>{
				if(item.key==e){
					radio = item;
				}
			});
			console.log(radio);
			console.log(this.form.buyNum);
			this.form.oldprice=radio.money;
			this.form.standardFee = radio.money*this.form.buyNum;
			this.form.totalFee=parseInt(this.form.standardFee)+parseInt(this.form.adjustmentFee)
		},
		
		dutyTimePickerChange(e) {
			console.log(e);
			this.form.bookDate = `${e.year}-${e.month}-${e.day}`;
		},
		cityChange(e) {
			console.log('cityChange', e);
			this.form.province= e.label[0];
			this.form.city=e.label[1];
			this.form.district=e.label[2];
			this.form.smc=e.key[2];
		},
		dutyTime2Confirm(e) {
			console.log(e);
			this.form.dutyTime2 = e[0].value;
			this.showForm.dutyTime2Show = e[0].label;
		},
		fileListChange(e) {
			console.log(e);
			this.fileList=e;
			console.log(e.photo);
		},
		photoChange(e){
			console.log(e.photo);
		},
		//拿预金额
		getMoney(){		
		   _appointPrePrice(this.form.No).then(response => {
		       this.form.appointPrePrice=response.data;
		      });
		},
		// 上传图片
		uploadFile(url,resForm){
		      console.info(resForm);
		      return new Promise((resolve, reject) => {
		             uni.uploadFile({
		                 url: baseUrl + appointPicOrderApiUrl,
		                 filePath: url,
		                 name: 'file',
		                  formData: {
		                        ...resForm,
		                  },
		                   success: (res) => {
		                      //因为我用的三方存储，所以将存储后的返回路径做了存储，
		                       //可能不同的accept返回的数据格式不同，所以处理数据的方式也不同
		                       //我在此处将上传三方库成功返回的路径进行了压栈存储
		                       //uploadImgs.push(JSON.parse(res.data).data.code)
		                     resolve(res)
							 console.log(res)
		                 }, 
		          });
		         });
				
		},
		
		// 存草稿
		draftClick(){
			// if(this.form.confirmPrice<=0){
			    console.log(this.form, this.fileList);
			     this.$refs.form.validate(valid => {
			          if (valid) {
			              this.updateSaveAppointOrder({
			                  ...this.form
			              }).then(res=>{
			                  if (res && res.code == 0) {
			                      //上传图片
			                      let res1 = this.fileList.map((item,index)=>{
			                               this.uploadFile(item.url,res.data);
			                        });
			                           // resolve(res1);
									   uni.showModal({
									   		title: '提示',
									   		content: '暂存成功',
									   		showCancel: false,
									   		success: function(res) {
									   			if (res1.confirm) {
									   				if(i==fileListLength-1){
									   					uni.navigateBack({
									   						delta:1
									   					});
									   				}
									   			}
									   		}
									   	});
			                     } else {
			                            uni.showModal({
			                                  mask: true,
			                                  title:'提交失败',
			                                 icon: 'none'
			                            });
			                        }
			                     }).all(res1).then(res1 => {
			                        });
			                
			              }
			            });
				// }else{
				// 	uni.showToast({
				// 		mask: true,
				// 		title: '暂存工单提交失败! 预充值金额不足请进行充值！',
				// 		icon: 'none'
				// 	});
				// }
		},
		
		// 提交 
		submitClick() {
			if(this.form.confirmPrice>=0){
				this.form.zt=1;
		        console.log(this.form, this.fileList);
		         this.$refs.form.validate(valid => {
		              if (valid) {
		                  this.updateSaveAppointOrder({
		                      ...this.form
		                  }).then(res=>{
		                      if (res && res.code == 0) {
		                          //上传图片
		                          let res1 = this.fileList.map((item,index)=>{
		                                   this.uploadFile(item.url,res.data);
		                            });
		                               // resolve(res1);
									   uni.showModal({
									   		title: '提示',
									   		content: '提交成功',
									   		showCancel: false,
									   		success: function(res) {
									   			if (res1.confirm) {
									   				if(i==fileListLength-1){
									   					uni.navigateBack({
									   						delta:1
									   					});
									   				}
									   			}
									   		},
											// setTimeout(() => {
											//        uni.switchTab({
											// 		url: './preStartOrderList'
											//      });
											// }, 600);
									   	});
		                         } else {
		                                uni.showModal({
		                                      mask: true,
		                                      title:'提交失败',
		                                     icon: 'none'
		                                });
		                            }
		                         }).all(res1).then(res1 => {
		                                 //所有图片上传成功时所需执行代码块
										//比如可以将upload函数中success 回调里压栈的数据发送给后台
		                            });
		                    
		                  }
		                      });
				}else{
					uni.showToast({
						mask: true,
						title: '工单提交失败! 预充值金额不足请进行充值！',
						icon: 'none'
					});
				}
		 },
		
	},
	
	watch:{
		'form.buyNum': {
		         handler: function() {
		          this.form.standardFee=this.form.oldprice*this.form.buyNum
				  console.log( this.form.oldprice)
				    console.log(12454)
				  this.form.totalFee=parseInt(this.form.standardFee)+parseInt(this.form.adjustmentFee)
		         },
		 },
		'form.adjustmentFee': {
			      handler: function() {
					  console.log(this.form.adjustmentFee)
					  if(this.form.adjustmentFee==""){
						   this.form.totalFee=parseInt(this.form.standardFee)
					  }else{
						this.form.totalFee=parseInt(this.form.standardFee)+parseInt(this.form.adjustmentFee)
						console.log(this.form.confirmPrice)  
					  }
			 	  
				  this.form.confirmPrice=parseInt(this.form.appointPrePrice)-parseInt(this.form.totalFee)
			     },
			    },
			'form.totalFee': {
				     handler: function() {
						this.form.confirmPrice=parseInt(this.form.appointPrePrice)-parseInt(this.form.totalFee)
					   },
			 }

		}
	
	
};
</script>

<style lang="less">
.container {
	padding: 12rpx 64rpx 94rpx 64rpx;
	.u-delete-icon {
		width: 30rpx !important;
		height: 30rpx !important;
	}
}
.bottomOpeCon {
	height: 94rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100vw;
	padding: 12rpx;
}
.actionimg{
	.imagesupload{
		
	}
	.imagesphoto{
		display: flex;
	}
}


</style>
